package worst.shopping.products;

import java.util.ArrayList;
import java.util.List;

import database.DataBaseKeys;
import database.Product;
import database.ProductDAO;
import worst.shopping.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

public class EditProductActivity extends Activity {
	
	private Product _product;
	private EditText _productName;
	private EditText _productUnit;
	private EditText _productPrice;
	private ImageButton _productImage;
	private Bitmap _productIcon;
	private ProductDAO _productDAO;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.productview);
		
		_productName = (EditText)findViewById(R.id.productview_productname);
		_productPrice = (EditText)findViewById(R.id.productview_price_edittext);
		_productUnit = (EditText)findViewById(R.id.productview_unit_edittext);
		_productImage = (ImageButton)findViewById(R.id.productImage);

		_productDAO = new ProductDAO(getApplication());	
		
		
		//this is a hack because the way android 2.1 handles orientation changes
		//is fucking retarded
		List<Object> data = (List<Object>)getLastNonConfigurationInstance();
		
		if(data != null)
		{
			//set data from previous activity
			_product = (Product)data.get(0);	
			
			Bitmap bitmap = (Bitmap)data.get(1);
			
			if(bitmap != null)
			{
				_productImage.setImageBitmap(bitmap);
				_productIcon = bitmap;
			}
		}
		else
		{
			//set data from database
			_product = _productDAO.getProduct(getIntent().getExtras().getString(DataBaseKeys.PRODUCT_NAME));

			if(_product != null)
			{
				_productName.setText(_product.getName());
				_productImage.setImageBitmap(_product.getIcon());
				_productPrice.setText(""+_product.getPrice());
				_productUnit.setText(_product.getUnit());
				_productIcon = _product.getIcon();
			}			
		}
	}
	
	public void saveButtonClicked(View view)
	{
		String productname = _productName.getText().toString();
		
		if(productname.equals(""))
		{
			showStupidProductNameDialog();
			return;
		}

		//there was no product to begin with...
		if(_product == null)
		{
			
			if(_productDAO.exists(productname))
			{
				showProductExistsDialog();
				return;
			}		
						
			//save a new product
			Product newProduct = new Product(
					productname, 
					_productIcon, 
					_productPrice.getText().toString(),
					_productUnit.getText().toString());
			
			_productDAO.insertProduct(newProduct);
		}
		else
		{
			//if anything has changed
			if(_product.getName().equals(_productName.getText().toString()) &&
					_product.getPrice().equals(_productPrice.getText().toString()) &&
					_product.getUnit().equals(_productUnit.getText().toString()) &&
					_product.getIcon().equals(_productIcon))
			{
				//nothing to do here
			}
			else
			{
				//update the existing product
				Product changedProduct = new Product(
						_productName.getText().toString(), 
						_productIcon, 
						_productPrice.getText().toString(),
						_productUnit.getText().toString());
				_productDAO.updateProduct(_product, changedProduct);				
			}
		}
		
		finish();
	}
	
	private void showStupidProductNameDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Enter a Product name");
		alert.setPositiveButton("Ok...", null);
		alert.show();
	}

	private void showProductExistsDialog() {
		final String productname = _productName.getText().toString();
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("A Product with the name '" + productname + "' already exists!");

		alert.setPositiveButton("Show existing", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
				Intent intent = getIntent();
				intent.putExtra(DataBaseKeys.PRODUCT_NAME, productname);
				finish();
				startActivity(intent);
		  }
		});

		alert.setNegativeButton("Continue edit", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Canceled.
		  }
		});

		alert.show();		
	}

	public void cancelButtonClicked(View view)
	{
		finish();
	}
	
	public void editImageButtonClicked(View view)
	{
		Intent intent = new Intent();
		//intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*"); 
		
		startActivityForResult(intent, 0);
	}
	
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
//            	_productIcon = (Bitmap) data.getExtras().get("data");	
                Uri selectedImageUri = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                String filePath = cursor.getString( cursor.getColumnIndex(filePathColumn[0]));
                cursor.close();

                Bitmap selectedImage = BitmapFactory.decodeFile(filePath);   

                _productIcon = Bitmap.createScaledBitmap(selectedImage, 96, 96, false);
            	_productImage.setImageBitmap(_productIcon);
            }
        }
    }	   
    
    @Override
    public Object onRetainNonConfigurationInstance() {
    	List<Object> data = new ArrayList<Object>();
    	
    	data.add(_product);
    	data.add(_productIcon);
    	
    	return data;
    }
}
